﻿
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;

using FreeSql;
using Kalman;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;

namespace QuDao
{
    /// <summary>
    /// 商品销售明细业务对象（处理数据表biz_goods_sales相关的业务逻辑）
    /// </summary>
    public sealed partial class GoodsSalesBO : SingletonBase<GoodsSalesBO>
    {
        readonly IFreeSql fsql;
        public GoodsSalesBO() : base()
        {
            fsql = ServiceLocator.Instance.GetRequiredService<IFreeSql>();
        }

        /// <summary>
        /// 获取商品销售明细
        /// </summary>
        /// <param name="id">主键ID的值</param>
        /// <returns></returns>
        public T GetItem<T>(long id)
        {
            if (id <= 0) return default;
            var item = fsql.Select<GoodsSales>().Where(a => a.ID == id).ToOne<T>();
            return item;
        }

        public GoodsSales GetItem(long id)
        {
            return GetItem<GoodsSales>(id);
        }

        /// <summary>
        /// 获取商品销售明细数据列表
        /// </summary>
        /// <param name="pageIndex">页索引，从1开始</param>
        /// <param name="pageSize">每页记录数，默认10</param>
        /// <returns></returns>
        public List<T> GetList<T>(int pageIndex = 1, int pageSize = 10)
        {
            var list = fsql.Select<GoodsSales>().Page(pageIndex, pageSize).ToList<T>();
            return list;
        }

        /// <summary>
        /// 获取商品销售明细数据列表
        /// </summary>
        /// <returns></returns>
        public List<T> GetList<T>(long[] ids)
        {
            if (ids == null || ids.Length == 0) return new List<T>();
            var list = fsql.Select<GoodsSales>().Where(a => ids.Contains(a.ID)).ToList<T>();
            return list;
        }

        /// <summary>
        /// 删除商品销售明细数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;
            return fsql.Delete<GoodsSales>().Where(a => ids.Contains(a.ID)).ExecuteAffrows();
        }

        /// <summary>
        /// 删除商品销售明细数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(long id)
        {
            return fsql.Delete<GoodsSales>(id).ExecuteAffrows();
        }

        /// <summary>
        /// 同步订单数据
        /// </summary>
        public void SyncOrderData(int tid, DateTime beginDate, DateTime endDate)
        {
            if (beginDate > endDate) throw new ArgumentException("开始日期不能晚于结束日期");
            var orderList = fsql.Select<Order>()
                .Where(a => a.TID == tid && a.CreateTime >= beginDate && a.CreateTime <= endDate && a.Status == (int)OrderStatus.已完成)
                .ToList(); //获取订单数据
            if (orderList.Count == 0) return; // 如果没有订单数据，直接返回

            var orderIDs = orderList.Select(a => a.OrderID).ToArray();
            var orderItemList = fsql.Select<OrderItem>()
                .Where(a => orderIDs.Contains(a.OrderID))
                .ToList();//获取订单项数据
            if (orderItemList.Count == 0) return; // 如果没有订单项数据，直接返回

            var orderDict = orderList.ToDictionary(o => o.OrderID); // 使用字典加速查找
            var list = new List<GoodsSales>();
            foreach (var item in orderItemList)
            {
                //var order = orderList.Find(p => p.OrderID == item.OrderID);
                if (!orderDict.TryGetValue(item.OrderID, out var order)) continue;

                var entity = new GoodsSales
                {
                    ID = item.OrderItemID,
                    TID = tid,
                    OrderID = item.OrderID,
                    GoodsID = item.GoodsID,
                    GoodsName = item.GoodsName,
                    CategoryID = item.CategoryID,
                    CategoryName = item.CategoryName,
                    UserID = item.UserID,
                    TrueName = order.TrueName,
                    AgentID = order.AgentID,
                    AgentName = order.AgentName,
                    Num = item.Num,
                    Price = item.Price,
                    CostPrice = item.CostPrice,
                    SalesAmount = item.Num * item.Price,
                    CostAmount = item.Num * item.CostPrice,
                    Commission = item.Num * item.Commission,
                    SalesDate = order.CreateTime.Date,
                    CreateTime = DateTime.Now
                };
                entity.DividedAmount = entity.SalesAmount - entity.CostAmount - entity.Commission;

                list.Add(entity);
            }

            if(list.Count > 0)
            {
                fsql.InsertOrUpdate<GoodsSales>().SetSource(list).ExecuteAffrows();
            }
                    
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="req">分页查询请求对象</param>
        public PagingResult<GoodsSales> Query(PagingRequest req, int tid, DateTime? beginDate, DateTime? endDate)
        {
            if (req == null) throw new AppException("查询数据不能为空");
            if (beginDate > endDate) throw new AppException("开始日期不能晚于结束日期");

            var select = fsql.Select<GoodsSales>().Where(a => a.TID == tid)
                .WhereIf(beginDate != null, a => a.SalesDate >= beginDate)
                .WhereIf(endDate != null, a => a.SalesDate <= endDate);
            foreach (var item in req.FilterItems)
            {
                switch (item.Field)
                {
                    case "UserID":
                        select.Where(a => a.UserID == long.Parse(item.Value));
                        break;
                    case "AgentID":
                        select.Where(a => a.AgentID == long.Parse(item.Value));
                        break;
                    case "GoodsID":
                        select.Where(a => a.GoodsID == int.Parse(item.Value));
                        break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(req.SortExp))
            {
                select.OrderBy(req.SortExp);//自定义排序
            }
            else
            {
                select.OrderByDescending(a => a.ID);//默认排序
            }

            //var sql = select.ToSql();

            var list = select.Count(out var total).Page(req.PageIndex, req.PageSize).ToList<GoodsSales>();
            //if (list.Count == 0 && beginDate != null && endDate != null)
            //{
            //    SyncOrderData(tid, beginDate ?? DateTime.MinValue, endDate ?? DateTime.Now);
            //    list = select.Count(out total).Page(req.PageIndex, req.PageSize).ToList<GoodsSales>();
            //}
            return new PagingResult<GoodsSales>
            {
                PageIndex = req.PageIndex,
                PageSize = req.PageSize,
                Data = list,
                Total = (int)total
            };
        }

    }
}
